package com.way.capture.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.way.capture.R;
import com.way.capture.base.BaseActivity;
import com.way.capture.fragment.GuideFragment;
import com.way.capture.utils.AppUtil;
import com.way.capture.utils.Utils;

import butterknife.BindView;
import butterknife.OnClick;

public class GuideActivity extends BaseActivity {
    private static final int NUM_PAGES = 4;
    @BindView(R.id.root_view)
    View mRootView;
    @BindView(R.id.button_layout)
    View mBottomBar;
    @BindView(R.id.pager)
    ViewPager mViewPager;
    @BindView(R.id.circles)
    LinearLayout mCirclesView;
    @BindView(R.id.skip)
    Button mSkipButton;
    @BindView(R.id.done)
    Button mDoneButton;
    @BindView(R.id.next)
    Button mNextButton;

    private boolean mIsOpaque = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        PagerAdapter pagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(pagerAdapter);
        mViewPager.setPageTransformer(true, new CrossFadePageTransformer());
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                if (position == NUM_PAGES - 2 && positionOffset > 0) {
                    if (mIsOpaque) {
                        mViewPager.setBackgroundColor(Color.TRANSPARENT);
                        mIsOpaque = false;
                    }
                } else {
                    if (!mIsOpaque) {
                        mViewPager.setBackgroundColor(getResources().getColor(R.color.primary_material_light));
                        mIsOpaque = true;
                    }
                }
            }

            @Override
            public void onPageSelected(int position) {
                setIndicator(position);
                if (position == NUM_PAGES - 2) {
                    mSkipButton.setVisibility(View.GONE);
                    mNextButton.setVisibility(View.GONE);
                    mDoneButton.setVisibility(View.VISIBLE);
                } else if (position < NUM_PAGES - 2) {
                    mSkipButton.setVisibility(View.VISIBLE);
                    mNextButton.setVisibility(View.VISIBLE);
                    mDoneButton.setVisibility(View.GONE);
                } else if (position == NUM_PAGES - 1) {
                    endTutorial();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        buildCircles();
        mRootView.setOnApplyWindowInsetsListener((v, insets) -> {
            mBottomBar.setPadding(insets.getSystemWindowInsetLeft(),
                    0,
                    insets.getSystemWindowInsetRight(),
                    insets.getSystemWindowInsetBottom() + Utils.dp2px(16));

            // clear this listener so insets aren't re-applied
            mRootView.setOnApplyWindowInsetsListener(null);
            return insets.consumeSystemWindowInsets();
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mViewPager != null) {
            mViewPager.clearOnPageChangeListeners();
        }
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_guide;
    }

    private void buildCircles() {
        mCirclesView = findViewById(R.id.circles);

        float scale = getResources().getDisplayMetrics().density;
        int padding = (int) (5 * scale + 0.5f);

        for (int i = 0; i < NUM_PAGES - 1; i++) {
            ImageView circle = new ImageView(this);
            circle.setImageResource(R.drawable.ic_swipe_indicator_white_18dp);
            circle.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT));
            circle.setAdjustViewBounds(true);
            circle.setPadding(padding, 0, padding, 0);
            mCirclesView.addView(circle);
        }

        setIndicator(0);
    }

    private void setIndicator(int index) {
        if (index < NUM_PAGES) {
            for (int i = 0; i < NUM_PAGES - 1; i++) {
                ImageView circle = (ImageView) mCirclesView.getChildAt(i);
                if (i == index) {
                    circle.setAlpha(1f);
                } else {
                    circle.setAlpha(0.5f);
                }
            }
        }
    }

    private void endTutorial() {
        PreferenceManager.getDefaultSharedPreferences(this).edit()
                .putBoolean(AppUtil.APP_FIRST_RUN, false).apply();
        finish();
        overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out);
    }

    @Override
    public void onBackPressed() {
        if (mViewPager.getCurrentItem() == 0) {
            //super.onBackPressed();
        } else {
            mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1);
        }
    }

    @OnClick({R.id.skip, R.id.done, R.id.next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.skip:
            case R.id.done:
                endTutorial();
                break;
            case R.id.next:
                mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1, true);
                break;
        }
    }

    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {

        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return String.valueOf(position + 1);
        }

        @Override
        public Fragment getItem(int position) {
            GuideFragment tp = null;
            switch (position) {
                case 0:
                    tp = GuideFragment.newInstance(R.layout.welcome_fragment1);
                    break;
                case 1:
                    tp = GuideFragment.newInstance(R.layout.welcome_fragment2);
                    break;
                case 2:
                    tp = GuideFragment.newInstance(R.layout.welcome_fragment3);
                    break;
                case 3:
                    tp = GuideFragment.newInstance(R.layout.welcome_fragment4);
                    break;
            }

            return tp;
        }

        @Override
        public int getCount() {
            return NUM_PAGES;
        }
    }

    public class CrossFadePageTransformer implements ViewPager.PageTransformer {

        @Override
        public void transformPage(View page, float position) {
            int pageWidth = page.getWidth();

            View backgroundView = page.findViewById(R.id.welcome_fragment);
            View textHead = page.findViewById(R.id.heading);
            View welcomeImage01 = page.findViewById(R.id.welcome_image);

            if (-1 < position && position < 1) {
                page.setTranslationX(pageWidth * -position);
            }

            if (-1 < position && position < 1 && position != 0) {
                if (backgroundView != null) {
                    backgroundView.setAlpha(1.0f - Math.abs(position));

                }

                if (textHead != null) {
                    textHead.setTranslationX(pageWidth * position);
                    textHead.setAlpha(1.0f - Math.abs(position));
                }

                if (welcomeImage01 != null) {
                    welcomeImage01.setTranslationX(pageWidth / 2 * position);
                    welcomeImage01.setAlpha(1.0f - Math.abs(position));
                }

            }
        }
    }
}
